Date Function and Conversion


Common usage


In [2]:
import datetime
from datetime import date

In [3]:
# Current date
date.today()


Out[3]:
datetime.date(2017, 10, 2)

In [6]:
# Save date into a variable 
d = date.today()
print('Today is ', d)


Today is  2017-10-02

In [12]:
# Convert to date if you have year, month and date
d = datetime.date(2017, 5, 18)
print('Date is ', d)


Date is  2017-05-18

In [10]:
# Convert date into ISO format
d.isoformat()


Out[10]:
'2017-05-18'

In [9]:
# Date format in 'Day DD. MON YYYY'
d.strftime("%A %d. %B %Y")


Out[9]:
'Thursday 18. May 2017'

In [13]:
# Date format in 'Day, DD-MON-YYYY'
d.strftime("%A, %d-%B-%Y")


Out[13]:
'Thursday, 18-May-2017'

In [16]:
# Calculate the date 7 days back from today
diffDate = date.today() - datetime.timedelta(days=7)
print('The date 7 days ago ', diffDate)


The date 7 days ago  2017-09-25

In [ ]: